<template>
  <div class="contractAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <!-- <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave()"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div> -->
    <el-collapse v-model="activeNames">
      
      <!-- 实收账期信息 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">巡检计划</span>
          <!-- <div
            class="nofixed-search-button button-position"
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div> -->
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.patrolSchemeAddInfoVos"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
            
          >
          
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
           
            <el-table-column
              label="计划开始时间"
              prop="startTime"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="计划结束时间"
              prop="endTime"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="责任人"
              prop="userId"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                <span
                  v-for="(item, index) in row.allotRelList"
                  :key="item.userId"
                  >{{ item.nickName
                  }}<span v-if="index + 1 !== row.allotRelList.length"
                    >，</span
                  ></span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="任务内容"
              prop="patrolScheme"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
          <div
            class="nofixed-search-button"
            style="position:static;margin-top:20px;"
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
        </div>
      </el-collapse-item>

      <!-- 账期结算收款 -->
      <el-collapse-item
        name="1"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">
            制定计划</span>
        </template>
        <div class="contract-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="120px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="责任人员：" prop="allotRelList">
                  <el-select
                    style="height: 101%"
                    v-model="contactForm.allotRelList"
                    class="search-input"
                    placeholder="请选择"
                    clearable
                    multiple
                    @change="userListChange"
                    value-key="userId"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计划开始时间：" prop="startTime">
                  <el-date-picker
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    v-model="contactForm.startTime"
                    class="search-input"
                    type="date"
                    placeholder="请选择"
                    @change="handleTimeChange(1)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计划结束时间：" prop="endTime">
                  <el-date-picker
                   format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    v-model="contactForm.endTime"
                    class="search-input"
                    type="date"
                    placeholder="请选择"
                    :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                    @change="handleTimeChange(2)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="personnelTableVisible">
              <el-table
                  v-loading="loading"
                  :data="allocationList"
                  border
                  height="16vh"
                  width="100%"
                  style="margin-bottom: 10px"
                  :header-cell-style="{ 'text-align': 'center' }"
              >
                <el-table-column
                    label="姓名"
                    prop="userName"
                    align="center"
                />
                <el-table-column
                    label="待开始任务"
                    prop="cnt0"
                    align="center"
                />
                <el-table-column
                    label="进行中任务"
                    prop="cnt1"
                    align="center"
                />
                <el-table-column
                    label="已逾期任务"
                    prop="cnt2"
                    align="center"
                />
                <el-table-column
                    label="操作"
                    align="center"
                >
                  <template #default="{ row, $index }">
                    <el-icon
                        title="查看详情"
                        color="#007CEF"
                        class="table-icon"
                        :size="20"
                        @click="handlePersonTable('detail', row)"
                    >
                      <Document />
                    </el-icon>
                    <el-icon
                        title="删除"
                        color="#E33838"
                        class="table-icon"
                        :size="20"
                        @click="handlePersonTable('delete', row, $index)"
                    >
                      <Delete />
                    </el-icon>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <el-row>
              <el-col :span="16">
                <el-form-item label="任务内容：" prop="patrolScheme">
                 

                  <el-input
              v-model="contactForm.patrolScheme"
              type="textarea"
              :rows="5"
              maxlength="500"
              placeholder="请填写"
            ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <!--  个人任务  -->
  <el-dialog
      :title="'个人任务'"
      v-model="personalTasksShow"
      width="1400px"
      append-to-body
  >
    <div class="task-container">
      <div class="task-container-left">
        <div>{{ infoPersonName }}</div>
        <div style="font-size: 16px;">{{ infoDeptName }}</div>
      </div>
      <div style="display: flex">
        <div
            class="personTask"
            v-for="(item, index) in personStatusList"
            :style="index === 0 ? 'background: rgb(240,248,244)' : index === 1 ? 'background: rgb(240,250,254)' : 'background: rgb(254,235,227)'">
          <span class="task-label">{{ item.label }}</span>
          <span class="task-number" :style="index == 0 ? 'color: green' : index == 1 ? 'color: blue' : 'color: red'">{{ item.number }}</span>
          <span class="task-label">个</span>
        </div>
      </div>
    </div>
    <div class="task-table">
      <div class="task-table-card" v-for="item in taskProjectList">
        <div class="task-content task-border" style="margin-top:0px;">
          <div class="task-border">
            <span>【{{ item.missionStatusName }}】</span>&nbsp;&nbsp;
            <span>{{ item.projectName }}</span>
          </div>
          <div class="timeConflict" v-if="item.status && item.missionTypeStatusName != '已完成'">时间段冲突</div>
        </div>
        <div class="task-content task-border">
          <div>
            <span>项目任务名称：</span>
            <span>{{ item.missionTypeName  || '--'}}</span>
          </div>
          <div>
            <span>任务状态：</span>
            <span>{{ item.missionTypeStatusName }}</span>
          </div>
        </div>
        <div class="task-content task-border">
          <div>
            <span>计划开始时间：</span>
            <span>{{ item.startTime }}</span>
          </div>
          <div>
            <span>计划结束时间：</span>
            <span>{{ item.endTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {getOrderCntDtlApi, getUserListApi, orderCntApi} from "@/api/operation/work";
import { getDeptListApi } from "@/api/information/customer";
import {
  pollingAddApi,
  pollingEditApi,
  getPollingApi,
} from "@/api/operation/project";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 回款新增组件显隐
  "followAddShow",
  // 更新回款组件显隐
  "update:followAddShow",
  // 刷新父组件表格数据
  "refreshList",
  "handleDetailInfo"
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
   // 操作类型
   rowdata: {
    type: Object,
    default: {},
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
//  详情加载效果
const detailInfoShow = ref(false);
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 下拉框引用
const refSelect = ref();
// 项目id
const projectId = ref(null);
//是否编辑
const editFlag = ref(false);
// 合同表单模板
const contractFormTemplate = {
  patrolSchemeAddInfoVos: [],
};
// 巡检删除列表(后端所需)
const deleteList = ref([]);
const data = reactive({
  //合同表单
  contractForm: JSON.parse(JSON.stringify(contractFormTemplate)),
  // 联系人表单
  contactForm: {
    allotRelList: [],
    startTime: "",
    endTime: "",
    patrolScheme: "",
    projectId: null,
  },
  // 校验规则
  queryContactRules: {
    deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
    allotRelList: [
      { required: true, message: "请选择巡检负责人员", trigger: "change" },
    ],
    startTime: [
      { required: true, message: "请选择计划开始时间", trigger: "change" },
    ],
    endTime: [
      { required: true, message: "请选择计划结束时间", trigger: "change" },
    ],
    patrolScheme: [
      { required: true, message: "请输入任务内容", trigger: "blur" },
    ],
  },
  // 账期列表
  paymentDaysList: [],
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
  // 项目列表
  projectList: [],
  // 是否列表
  flagList: [
    {
      label: "是",
      value: 0,
    },
    {
      label: "否",
      value: 1,
    },
  ],
});
const {
  contractForm,
  contactForm,
  queryContactRules,
  paymentDaysList,
  userList,
  deptList,
  projectList,
  flagList,
} = toRefs(data);
const contactAddShow = ref(false);
// 任务分配弹窗
const taskAllocationShow = ref(false);
// 选择责任人员显示的表格
const personnelTableVisible = ref(false);
const personalTasksShow = ref(false);
// 责任人员下拉列表
// const userList = ref([]);
// 任务分配表单ref
const projectFormRef = ref();
// 任务分配对象
const projectForm = ref({
  startTime: "",
  endTime: "",
  userList: [],
  remark: ''
});
// 任务分配表单
const allocationList = ref([]);


/*
* 任务分配取消
* */
const clearAllocation = () => {
  taskAllocationShow.value = false;
  projectForm.value = {
    startTime: "",
    endTime: "",
    userList: [],
    remark: ''
  }
  allocationList.value = [];
  personnelTableVisible.value = false;
}

/*
* 根据责任人筛选查询表格
* */
const userListChange = (value) => {
  if (value.length > 0) {
    personnelTableVisible.value = true;
    let list = value.map(item => item = item.userId)
    let params = {
      userIds: list
    }
    orderCntApi(params).then(res => {
      if (res) {
        allocationList.value = res
      }
    })
  }else {
    personnelTableVisible.value = false;
  }
}


/*
*
* 时间戳转换*/
const nowDate = (now) => {
  const date = new Date(now)
  const time = date.getTime() // 精确到毫秒
  return time;
}
const personStatusList = ref([])
const taskProjectList = ref([])
/*
* 责任人员表格操作按钮
* */
let infoPerson = null;
let infoPersonName = "";
let infoDeptName = "";
const handlePersonTable = (type, row, index) => {
  switch (type) {
    case 'detail':
      infoPerson = row;
      personalTasksShow.value = true;
      personStatusList.value = [
        {
          label: '待开始',
          number: row.cnt0
        },
        {
          label: '进行中',
          number: row.cnt1
        },
        {
          label: '已逾期',
          number: row.cnt2
        }
      ]
      getOrderCntDtlApi({userId: row.userId }).then(res => {
        if (res) {
          taskProjectList.value = res
          infoPersonName = taskProjectList.value[0].userName;
          infoDeptName = taskProjectList.value[0].deptName;
          let startTime = null;
          let endTime = null;
          if (!!contactForm.value.startTime || !!contactForm.value.endTime) {
            startTime = nowDate(contactForm.value.startTime);
            endTime = nowDate(contactForm.value.endTime);
          }else{
            startTime = null;
            endTime = null;
          }
          taskProjectList.value.map(item => {
            let actionStatTime = nowDate(item.startTime)
            let actionEndTime = nowDate(item.endTime)
            if (!!startTime || !!endTime) {
              if (startTime >= actionStatTime && startTime <= actionEndTime) {
                item.status = true;
              }else if (endTime >= actionStatTime && startTime <= actionEndTime) {
                item.status = true;
              }
            }else {
              item.status = false;
            }
          })
        }
      })
      break;
    case 'delete':
      console.log("11", contactForm.value.allotRelList)
      allocationList.value.splice(index, 1);
      contactForm.value.allotRelList.splice(index, 1);
      break;
    default:
      break;
  }
}


/**
 * @description: 保存
 */
const handleraddbusSchedule = async () => {
  if (!contractForm.value.patrolSchemeAddInfoVos.length) {
    return ElMessage.warning("请添加巡检计划！");
  }
  ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      let res;
      console.log(editFlag.value)
      if (!editFlag.value) {
        
        res = await pollingAddApi(contractForm.value);
      } else {
        const obj = {
          deletePatrolSchemeAddInfoVos: deleteList.value,
          patrolSchemeAddInfoVos: contractForm.value.patrolSchemeAddInfoVos,
        };
        res = await pollingEditApi(obj);
      }

      if (res.code === 200) {
        emit("update:followAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:followAddShow", false);
    contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:followAddShow", false);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      // let userFlag;
      // let timeFlag;
      // contractForm.value.patrolSchemeAddInfoVos.some((item) => {
      //   userFlag = false;
      //   timeFlag = false;
      //   // 检测有没有相同负责人员
      //   contactForm.value.allotRelList.forEach((childItem) => {
      //     item.allotRelList.forEach((graItem) => {
      //       if (childItem.userId === graItem.userId) {
      //         userFlag = true;
      //       }
      //     });
      //   });
      //   // 检测有没有相同日期
      //   if (item.inspectionDates == contactForm.value.inspectionDates) {
      //     timeFlag = true;
      //   }
      //   if (userFlag && timeFlag) {
      //     return true; // 跳出循环
      //   }
      // });
      // //  && contactForm.value.patrolSchemeId
      // if (userFlag && timeFlag) {
      //   return ElMessage.warning("该人员在此日期已有任务！");
      // }

      if (operateType.value === "edit") {
        contractForm.value.patrolSchemeAddInfoVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        contractForm.value.patrolSchemeAddInfoVos.push({
          ...JSON.parse(JSON.stringify(contactForm.value)),
          projectId: projectId.value,
        });
      }
      allocationList.value = [];
      contactForm.value = {};
      contactFormRef.resetFields();
      nextTick(() => {
        refSelect.value.focus();
      });
      operateType.value = "add";
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理时间变更
 */
const handleTimeChange = (flag) => {
  if (contactForm.value.startTime && contactForm.value.endTime && contactForm.value.startTime > contactForm.value.endTime) {
    ElMessage.info("计划开始时间不能大于计划结束时间！");
    if (flag == 1) {
      contactForm.value.startTime = "";
    } else {
      contactForm.value.endTime = "";
    }
  }};

/**
 * @description: 处理销售清单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refSelect.value.focus();
    });
  } else {
    deleteList.value.push(JSON.parse(JSON.stringify(row)));
    contractForm.value.patrolSchemeAddInfoVos.splice(tabIndex, 1);
  }
};
/**
 * @description: 处理部门选择
 * @param {Number} value 当前值
 */
const handleDepart = async (value, flag = true) => {
  if (flag) {
    contactForm.value.allotRelList = [];
  }
  if (value) {
    const selectDept = deptList.value.find((dept) => dept.deptId === value);
    // 打印所选部门信息
    console.log(selectDept);
    if (selectDept) {
      await getUserListApi(selectDept.deptType).then((res) => {
        if (res) {
          userList.value = res;
        }
      });
    } else {
      userList.value = [];
    }
  } else {
    userList.value = [];
  }
};
/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async () => {
  console.log('props.rowdata.projectId')
  console.log(props.rowdata.projectId)
  projectId.value = props.rowdata.projectId;
  try {
    detailInfoShow.value = true;
    const res = await getPollingApi(props.rowdata.projectId);
    console.log('res1')
    console.log(res)
    if (res.length) {
      console.log('???')
      editFlag.value = true;
    }
    contractForm.value.patrolSchemeAddInfoVos = res;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_account_period").then((res) => {
    if (res.code === 200) {
      paymentDaysList.value = res.data;
    }
  });
  await getDeptListApi().then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
    }
  });
  await getUserListApi(2).then((res) => {
    if (res) {
      userList.value = res;
    }
  });
}

onMounted(() => {
  getDicts();
  handleDetailInfo()
  nextTick(() => {
    refSelect.value.focus();
  });
});

defineExpose({
  handleDetailInfo,handleraddbusSchedule
});
</script>
<style lang="scss" scoped>
.contractAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  // :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  //   width: 268px !important;
  //   height: 34px !important;
  // }

  // .search-input {
  //   width: 268px;
  //   height: 34px;
  // }
  .contract-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding: 20px 0;
  }
  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  //   :deep(.el-select) {
  //     width: 100%;
  //     // min-height: 50px !important;
  //     height: 100% !important;
  //     .el-input__wrapper {
  //       // min-height: 50px !important;
  //       height: inherit !important;
  //     }
  //     .el-input__inner {
  //       height: 100% !important;
  // }
  //   }
}
.task-container{
  width: 100%;
  //border: 1px red solid;
  display: flex;
  justify-content: space-between;
  .task-container-left{
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;

    div:first-child{
      font-weight: 600;
      font-size: 24px;
      color: black;
    }
  }
}
.task-table{
  width: 100%;
  height: 61vh;
  overflow: hidden;
  overflow-y: scroll;
  margin-top: 20px;
  .task-table-card{
    width: 100%;
    height: 185px;
    border: 1px rgb(215, 215, 215) solid;
    border-radius: 10px;
    padding: 0px 15px;
    font-size: 15px;
    margin-bottom: 20px;
    .task-border{
      margin-top: 30px;
    }
    .task-content{
      display: flex;
      justify-content: space-between;
    }
    .timeConflict{
      margin-top:20px;
      width: 120px;
      height: 45px;
      color: rgb(247, 98, 128);
      background: rgb(254, 244, 231);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.personTask{
  width: 140px;
  height: 110px;
  border-radius: 10px;
  margin: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;

  .task-label{
    font-size: 16px;
    color: black;
  }

  .task-number{
    font-size: 20px;
    font-weight: 700;
  }
}

</style>
